package com.lzx.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.article.entity.Articles;
import com.lzx.article.entity.Browse;
import com.lzx.article.mapper.ArticlesMapper;
import com.lzx.article.mapper.BrowseMapper;
import com.lzx.article.service.BrowseService;
import com.lzx.common.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 浏览记录 服务实现类
 * </p>
 *
 * @author lzx
 * @since 2023-02-04
 */
@Service
public class BrowseServiceImpl extends ServiceImpl<BrowseMapper, Browse> implements BrowseService {
    @Resource
    private BrowseMapper browseMapper;

    @Resource
    private ArticlesMapper articlesMapper;

    //保存用户浏览文章记录
    @Override
    public R saveUserBrowse(Browse browse) {
        QueryWrapper<Browse> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", browse.getUserId()).eq("article_id", browse.getArticleId());
        Browse vo = browseMapper.selectOne(wrapper);
        browse.setBrowseTime(new Date());
        //如果浏览记录存在，则更新浏览时间，否则保存浏览记录
        if (vo != null) {
            vo.setBrowseTime(new Date());
            browseMapper.updateById(vo);
        } else {
            browse.setBrowseTime(new Date());
            browseMapper.insert(browse);
            //文章浏览量+1
            Articles articles = articlesMapper.selectById(browse.getArticleId());
            articles.setViews(articles.getViews() + 1);
            articlesMapper.updateById(articles);
        }
        return R.ok().message("保存成功");
    }

    //通过用户id获取用户浏览记录
    @Override
    public R getBrowseArticle(Long userId) {
        return R.ok().data("list", getUserBrowseList(userId));
    }

    //通过用户id获取用户浏览记录(提供给用户服务)
    @Override
    public List<Browse> getArticleBrowseListToUser(Long userId) {
        return getUserBrowseList(userId);
    }

    //获取用户浏览记录
    private List<Browse> getUserBrowseList(Long userId) {
        QueryWrapper<Browse> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Browse> articleList = browseMapper.selectList(wrapper);
        for (Browse browse : articleList) {
            Articles articles = articlesMapper.selectById(browse.getArticleId());
            articles.setLabels(Arrays.asList(articles.getLabelTranslation().split(",")));
            browse.setArticles(articles);
        }
        return articleList;
    }
}
